<template>
    <view class="container">
        <view class="header">
            <text class="title">AI语音聊天</text>
        </view>
        
        <view class="agent-container">
            <view class="agent-avatar">
                <image src="/static/agent/agent.jpg" class="avatar-image" />
            </view>
            <view class="thinking-status" v-if="isThinking">
                <view class="thinking-dots">
                    <view class="thinking-dot dot1"></view>
                    <view class="thinking-dot dot2"></view>
                    <view class="thinking-dot dot3"></view>
                </view>
                <text class="thinking-text">思考中...</text>
            </view>
        </view>
        
        <view class="footer">
            <view class="footer-btn" @click="showSpeedPopup">
                <image src="/static/agent/ys.png" class="footer-icon" />
                <text class="footer-text">切换语速</text>
            </view>
            
            <view class="footer-btn center-btn">
                <view class="microphone-btn" @touchstart="startRecording" @touchend="stopRecording">
                    <image src="/static/mine/sound.png" class="microphone-icon" />
                    <text class="microphone-text">{{ isRecording ? '正在录音...' : '点击说话' }}</text>
                </view>
            </view>
            
            <view class="footer-btn" @click="confirmEndCall">
                <image src="/static/agent/g.png" class="footer-icon" />
                <text class="footer-text">挂断</text>
            </view>
        </view>
        
        <!-- 语速弹窗 -->
        <view class="popup-container" v-if="isSpeedPopupVisible">
            <view class="popup-content">
                <text class="popup-title">调整语速</text>
                <slider class="speed-slider" :value="currentSpeed" min="0.5" max="2" step="0.1" show-value @change="onSpeedChange" />
                <view class="popup-buttons">
                    <view class="popup-btn cancel-btn" @click="closeSpeedPopup">取消</view>
                    <view class="popup-btn confirm-btn" @click="confirmSpeedChange">确认</view>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup>
    import { ref } from 'vue';
    import { onLoad } from '@dcloudio/uni-app';
    import { ApiVoicetoVoice, ApiTextToVoice } from '../api/agent';

    // 音频播放相关
    const audioUrl = ref('');
    const isPlaying = ref(false);
    const audioContext = uni.createInnerAudioContext();

    // 播放/暂停音频
    const toggleAudioPlay = () => {
        if (!audioUrl.value) return;
        
        if (isPlaying.value) {
            audioContext.pause();
        } else {
            audioContext.src = audioUrl.value;
            audioContext.play();
        }
        
        isPlaying.value = !isPlaying.value;
    };

    // 音频播放结束事件
    audioContext.onEnded(() => {
        isPlaying.value = false;
    });

    // 播放错误处理
    audioContext.onError((res) => {
        console.error('音频播放错误：', res.errMsg);
        uni.showToast({
            title: '音频播放失败',
            icon: 'none'
        });
    });

    // 录音相关逻辑
    const isSpeedPopupVisible = ref(false);
    const isRecording = ref(false);
    const isThinking = ref(false);
    const currentSpeed = ref(1.0);
    const recorderManager = uni.getRecorderManager();
    let tempFilePath = ''; // 用于存储录音文件路径

    const startRecording = () => {
        if (isRecording.value) return;
        
        isRecording.value = true;
        
        const options = {
            format: 'mp3',
            sampleRate: 16000,
            numberOfChannels: 1,
            encodeBitRate: 128000
        };
        
        recorderManager.start(options);
        console.log('开始录音');
    }

    const stopRecording = async () => {
        if (!isRecording.value) return;
        
        isRecording.value = false;
        isThinking.value = true;
        
        recorderManager.stop();
    }

    // 录音停止后的处理
    recorderManager.onStop(async (res) => {
        tempFilePath = res.tempFilePath;
        console.log('录音文件路径：', tempFilePath);
        console.log('停止录音');
        
        // 直接将录音文件上传到服务器
        try {
            isThinking.value = true;
            const textResult = await ApiVoicetoVoice(tempFilePath);
            console.log('语音转文本结果：', textResult);
            
            // 转换文本为语音
            const voiceResult = await ApiTextToVoice(textResult);
            console.log('文本转语音结果：', voiceResult);
            
            // 播放AI返回的语音
            playAudio(voiceResult);
        } catch (error) {
            console.error('语音处理失败：', error);
            uni.showToast({
                title: '语音处理失败',
                icon: 'none'
            });
        } finally {
            isThinking.value = false;
        }
    });

    // 播放音频
    const playAudio = (audioSrc) => {
        audioUrl.value = audioSrc;
        audioContext.src = audioSrc;
        audioContext.play();
        isPlaying.value = true;
    };

    // 语速弹窗逻辑
    const showSpeedPopup = () => {
        isSpeedPopupVisible.value = true;
    }
    
    const closeSpeedPopup = () => {
        isSpeedPopupVisible.value = false;
    }
    
    const onSpeedChange = (e) => {
        currentSpeed.value = parseFloat(e.detail.value.toFixed(1));
    }
    
    const confirmSpeedChange = () => {
        console.log('设置语速为：', currentSpeed.value);
        isSpeedPopupVisible.value = false;
        audioContext.playbackRate = currentSpeed.value;
    }
    
    // 挂断电话逻辑
    const confirmEndCall = () => {
		console.log("a")
        uni.showModal({
            title: '提示',
            content: '是否确认挂断?',
            success: function (res) {
                if (res.confirm) {
                    console.log('用户确认挂断');
                    uni.navigateBack();
                } else if (res.cancel) {
                    console.log('用户取消挂断');
                }
            }
        });
    }
</script>

<style scoped>
    .container {
        width: 100%;
        height: 100vh;
        background-color: #eef3fa;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: space-between;
        padding: 20rpx;
        box-sizing: border-box;
    }
    
    .header {
        width: 100%;
        text-align: center;
        padding-top: 30rpx;
    }
    
    .title {
        font-size: 36rpx;
        font-weight: bold;
        color: #333333;
    }
    
    .agent-container {
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 30rpx 0;
    }
    
    .agent-avatar {
        width: 500rpx;
        height: 500rpx;
        border-radius: 50%;
        background-color: #ffffff;
        position: relative;
        overflow: hidden;
        margin-bottom: 30rpx;
    }
    
    .avatar-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    
    .thinking-status {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }
    
    .thinking-dots {
        display: flex;
        justify-content: center;
        margin-bottom: 20rpx;
    }
    
    .thinking-dot {
        width: 20rpx;
        height: 40rpx;
        background-color: #4a90e2;
        margin: 0 5rpx;
        border-radius: 5rpx;
    }
    
    .dot1 {
        animation: thinking 1.2s infinite;
    }
    
    .dot2 {
        animation: thinking 1.2s infinite 0.2s;
    }
    
    .dot3 {
        animation: thinking 1.2s infinite 0.4s;
    }
    
    .thinking-text {
        color: #4a90e2;
        font-size: 28rpx;
        text-align: center;
    }
    
    @keyframes thinking {
        0%, 100% {
            height: 40rpx;
            opacity: 0.5;
        }
        50% {
            height: 60rpx;
            opacity: 1;
        }
    }
    
    .footer {
        width: 100%;
        display: flex;
        justify-content: space-around;
        padding: 30rpx 0;
    }
    
    .footer-btn {
        display: flex;
        flex-direction: column;
        align-items: center;
    }
    
    .footer-icon {
        width: 80rpx;
        height: 80rpx;
        margin-bottom: 10rpx;
    }
    
    .footer-text {
        font-size: 26rpx;
        color: #666666;
    }
    
    .center-btn {
        display: flex;
        justify-content: center;
    }
    
    .microphone-btn {
        width: 160rpx;
        height: 160rpx;
        background-color: #ffffff;
        border-radius: 50%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.1);
    }
    
    .microphone-icon {
        width: 60rpx;
        height: 60rpx;
        margin-bottom: 10rpx;
    }
    
    .microphone-text {
        font-size: 24rpx;
        color: #999999;
    }
    
    .popup-container {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 1000;
    }
    
    .popup-content {
        width: 80%;
        max-width: 500rpx;
        background-color: #ffffff;
        border-radius: 20rpx;
        padding: 40rpx;
        box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
    }
    
    .popup-title {
        font-size: 36rpx;
        font-weight: bold;
        margin-bottom: 30rpx;
        text-align: center;
        color: #333;
    }
    
    .speed-slider {
        width: 100%;
        margin-bottom: 40rpx;
    }
    
    .popup-buttons {
        display: flex;
        justify-content: space-between;
        margin-top: 30rpx;
    }
    
    .popup-btn {
        width: 45%;
        height: 80rpx;
        border-radius: 20rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 32rpx;
        font-weight: 500;
    }
    
    .cancel-btn {
        background-color: #f0f0f0;
        color: #333;
        border: 1px solid #e0e0e0;
    }
    
    .confirm-btn {
        background-color: #4a90e2;
        color: #fff;
        border: 1px solid #4a90e2;
    }
</style>